package com.ruike.alisurface.ui;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.google.gson.Gson;
import com.hjq.xtoast.XToast;
import com.ruike.alisurface.BuildConfig;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.CarGoodsBeans;
import com.ruike.alisurface.bean.ShopInfoBean;
import com.ruike.alisurface.bean.ShopOrderBean;
import com.ruike.alisurface.bean.ShoptypeBean;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.QrCodeUtils;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.service.MyFileOtherService;
import com.ruike.alisurface.ui.adapters.QrCodeAdapter;
import com.ruike.alisurface.ui.adapters.ShopCarAdapter;
import com.ruike.alisurface.ui.adapters.ShopModelAdapter;
import com.ruike.alisurface.ui.adapters.ShopTyepAdapter;
import com.ruike.alisurface.ui.adapters.ShopinfoAdapter;
import com.ruike.alisurface.ui.adv.Adv_Aty;
import com.ruike.alisurface.ui.payPage.ShopPayType_Aty;
import com.ruike.alisurface.utils.ButtonUtils;
import com.ruike.alisurface.utils.CopyUtils;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.FinalDbUtils;
import com.ruike.alisurface.utils.GsonUtils;
import com.ruike.alisurface.utils.PxUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.Type_toGoshopzl;

/**
 * 药品展示页
 */
public class ShopMain_Aty extends BaseAty implements ApiListener {
    @BindView(R.id.main_temperature)
    TextView mainTemperature;
    @BindView(R.id.main_humidity)
    TextView mainHumidity;
    @BindView(R.id.main_shoptype_recyclerView)
    RecyclerView mainShoptypeRecyclerView;
    @BindView(R.id.main_shoptype_model_recyclerView)
    RecyclerView mainShoptypeModelRecyclerView;
    @BindView(R.id.main_shop_recyclerView)
    RecyclerView mainShopRecyclerView;
    @BindView(R.id.main_goback)
    ImageView mainGoback;
    @BindView(R.id.main_carshop_recyclerView)
    RecyclerView mainCarshopRecyclerView;
    @BindView(R.id.main_settleaccounts)
    LinearLayout mainSettleaccounts;
    @BindView(R.id.main_left_all_img)
    ImageView mainLeftAllImg;
    @BindView(R.id.main_left_all_ly)
    RelativeLayout mainLeftAllLy;

    @BindView(R.id.main_line)
    View mainLine;
    @BindView(R.id.main_line_range)
    LinearLayout mainLineRange;
    @BindView(R.id.car_clear_tv)
    TextView mCarClear;

    @BindView(R.id.errordata_ly)
    LinearLayout errordata_ly;
    @BindView(R.id.updata_tv)
    TextView updata_tv;

    Handler mHandle = new Handler();

    ShoptypeBean shopTypeBean;//所有的药品类型级别数据
    ShopModelAdapter shopModelAdapter;
    ShopInfoBean shopInfoBean;

    ShopTyepAdapter shopTyepAdapter;//药品类型三级适配器
    List<ShoptypeBean.DataBean.ChildrenBeanX.ChildrenBean> mlist = new ArrayList<>();

    @BindView(R.id.main_qualification)
    ImageView mainQualification;
    private ShopinfoAdapter shopInfoAdapter;//药品详情适配器
    List<ShopInfoBean.DataBean> mShopLvBeanList = new ArrayList<>();//药品详情集合

    ShopCarAdapter shopCarAdapter;//购物车适配器

    List<ShopInfoBean.DataBean> carShopList = new ArrayList<>();//购物车集合

    ShopOrderBean shopOrderBean;//订单信息类

    List<ShoptypeBean.DataBean> mModelList = new ArrayList<>();//药品类型数据


    @Override
    protected int getLayoutResId() {
        return R.layout.app_activity_main;
    }

    int purchaseCount;//最大购买数量
    int advType;

    @SuppressLint("DefaultLocale")
    @Override
    protected void initViews() {
        advType = SharedUtils.getInstance().getInt(Constant.AdvType.ADV_TYPE_KEY);
        initTitleBar(advType == Constant.AdvType.NONE);
        if (advType == Constant.AdvType.NONE) {
            mainGoback.setVisibility(View.INVISIBLE);
        } else {
            startCountdownTimer(120, null, Adv_Aty.class);
            mainGoback.setVisibility(View.VISIBLE);
            mainGoback.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(Adv_Aty.class, null);
                    finish();
                }
            });
        }
        purchaseCount = SharedUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT, 3);
        mainTemperature.setText(String.format("温度 %d℃", SharedUtils.getInstance().getInt(ShareKey.TEMPERATURE)));
        mainHumidity.setText(String.format("湿度 %d%%", SharedUtils.getInstance().getInt(ShareKey.HUMIDITY)));

        mainQualification.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(Qualification_Aty.class, null);
                finish();
            }
        });
        updata_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDataProduct("", "", "");
                getProductType();
            }
        });
    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onStart() {
        super.onStart();
        FinalDbUtils.getInstance().deleteAll(CarGoodsBeans.class);
    }

    @Override
    protected void onResume() {
        super.onResume();
        ShopApiHttp.get_mch_logo(this);
        ShopApiHttp.get_mch_max_sale_count(this);
    }

    @Override
    protected void initData() {
        setDataProduct("", "", "");
        getProductType();
        setDataProductType();
        carShopData();
        mainSettleaccounts.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (carShopList.size() <= 0) {
                    showToast("请先选择商品");
                    return;
                }
                if (Constant.isShopShipment) {
                    L.i("已经在通信中了");
                    return;
                }

                if (ButtonUtils.isFastDoubleClick(view.getId())) {
                    L.i("已经点击了结算");
                    return;
                }
                L.i("点击了结算 串口底层通信中");
                showToast("创建订单中，请等待...");
                Constant.isShopShipment = true;
                Ttys3Utils.getInstance().ledOpenOrClose(0, 2, true, 15, 15);
                startTime(3, 0);
                if (BuildConfig.DEBUG) {
                    EventBus.getDefault().post(new MsgEventBus(Type_toGoshopzl, "10020618"));
                }
            }
        });

    }


    /**
     * 获取药品类型级别
     * 回调其点击事件
     */
    public void setDataProductType() {

        if (shopModelAdapter == null) {
            shopModelAdapter = new ShopModelAdapter(mModelList);
            mainShoptypeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
            mainShoptypeRecyclerView.setAdapter(shopModelAdapter);
        }

        shopModelAdapter.setOnItemClickListener(new ShopModelAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, ShoptypeBean.DataBean data) {
                mainLeftAllImg.setImageResource(R.drawable.icon_item_wxz);
                if (shopTyepAdapter != null) {
                    mlist.clear();
                    shopTyepAdapter.setList(mlist);
                }
                if (shopModelAdapter.isExpanded(position)) {
                    shopModelAdapter.setChildUpdata();
                    mModelList.clear();
                    mModelList.addAll(shopTypeBean.getData());
                    shopModelAdapter.collapseAllGroup();
                } else {

                    shopModelAdapter.setChildUpdata();
                    shopModelAdapter.collapseAllGroup();
                    shopModelAdapter.expandGroup(position);
                }
                L.i("shopModelAdapter=", "onItemClick    " + data.toString(), shopModelAdapter.isExpanded(position));
                mHandle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (shopInfoBean != null) {
                            setShopListData(data.getValue(), shopInfoBean);
                        }
                    }
                }, 100);

                shopModelAdapter.notifyDataSetChanged();

            }

            @Override
            public void onItemChildClick(int groupposition, int position, ShoptypeBean.DataBean.ChildrenBeanX data) {
                Log.i("shopModelAdapter=", "onItemChildClick 组id ==" + groupposition + "子id==" + position + data.toString());
                mHandle.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mainLeftAllImg.setImageResource(R.drawable.icon_item_wxz);
                        shopModelAdapter.setChildUpdataAdapter(groupposition, position, data);
                        setTopListData(data);
                        if (shopInfoBean != null) {
                            setShopListData(data.getValue(), shopInfoBean);
                        }
                    }
                }, 100);

            }
        });


        mainLeftAllLy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mainLeftAllImg.setImageResource(R.drawable.icon_item_xz);
                if (shopTypeBean == null || shopTypeBean.getData() == null) {
                    return;
                }
                shopModelAdapter.setChildUpdata();
                mModelList.clear();
                mModelList.addAll(shopTypeBean.getData());
                shopModelAdapter.collapseAllGroup();
                if (shopTyepAdapter != null) {
                    mlist.clear();
                    shopTyepAdapter.setList(mlist);
                }
                if (shopInfoBean != null) {
                    setShopListData("", shopInfoBean);
                }
            }
        });
    }


    public void setDataProduct(String lv1, String lv2, String lv3) {
        showProgressDialog("加载药品数据中，请等待...");
        ShopApiHttp.get_product(lv1, lv2, lv3, this);

    }

    public void getProductType() {
        ShopApiHttp.get_product_type(this);
    }

    /**
     * 设置药品的三级类型
     *
     * @param childrenBeanX
     */
    public void setTopListData(ShoptypeBean.DataBean.ChildrenBeanX childrenBeanX) {
        mlist.clear();
        if (shopTyepAdapter == null) {
            shopTyepAdapter = new ShopTyepAdapter(R.layout.main_top_list_item, mlist, this);
            mainShoptypeModelRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
            mainShoptypeModelRecyclerView.setAdapter(shopTyepAdapter);
        }

        if (childrenBeanX.getChildren().size() > 0) {
            ShoptypeBean.DataBean.ChildrenBeanX.ChildrenBean mChildrenBean = new ShoptypeBean.DataBean.ChildrenBeanX.ChildrenBean();
            mChildrenBean.setLabel("全部");
            mChildrenBean.setSelect(true);
            mChildrenBean.setValue(childrenBeanX.getValue());
            mlist.add(mChildrenBean);
        }
        mHandle.post(new Runnable() {
            @Override
            public void run() {
                mlist.addAll(CopyUtils.depCopy(childrenBeanX.getChildren()));
                shopTyepAdapter.setList(mlist);
            }
        });
        shopTyepAdapter.setOnItemClickListener((adapter, view, position) -> {
            if (!mlist.get(position).isSelect() && shopInfoBean != null) {
                setShopListData(mlist.get(position).getValue(), shopInfoBean);
            }
            for (int i = 0; i < mlist.size(); i++) {
                mlist.get(i).setSelect(false);
            }
            mlist.get(position).setSelect(true);
            Log.i("ces=", "shopTyepAdapter点击的item  " + position + "===" + mlist.get(position).toString());
            shopTyepAdapter.setList(mlist);
        });
    }


    /**
     * 设置药品详细信息
     *
     * @param lv 药品类型级别 value
     */
    public void setShopListData(String lv, @Nullable ShopInfoBean shopInfoBean) {
        mShopLvBeanList.clear();
        if (shopInfoAdapter == null) {
            shopInfoAdapter = new ShopinfoAdapter(
                    mShopLvBeanList, this);
            mainShopRecyclerView.setLayoutManager(new GridLayoutManager(this, 3, RecyclerView.HORIZONTAL, false));
            mainShopRecyclerView.setAdapter(shopInfoAdapter);
            shopInfoAdapter.setEmptyView(R.layout.item_emptyview);
            L.i("药品  2-====     " + mShopLvBeanList.size());

            mainShopRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
                    if (mShopLvBeanList.size() > 9) {//
                        //整体的总宽度，注意是整体，包括在显示区域之外的。
                        int temp = recyclerView.computeHorizontalScrollRange();
                        //计算水平滚动的距离
                        int offset = recyclerView.computeHorizontalScrollOffset();
                        //计算水平滚动的范围
                        int extent = recyclerView.computeHorizontalScrollExtent();
                        //计算滑动比例
                        float proportion = (float) (offset * 1.0 / (temp - extent));
                        //计算滚动条宽度
                        float transMaxRange = mainLineRange.getWidth() - mainLine.getWidth();
                        //设置滚动条移动

                        mainLine.setTranslationX(transMaxRange * proportion);
                    }
                }
            });

            shopInfoAdapter.setOnItemClickListener((adapter, view, position) -> addCar(position, mShopLvBeanList.get(position)));
            mCarClear.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for (ShopInfoBean.DataBean dataCarBean : carShopList) {
                        delectCar(dataCarBean);
                    }
                    carShopList.clear();
                    shopCarAdapter.notifyDataSetChanged();
                }
            });

            shopInfoAdapter.addChildClickViewIds(R.id.product_details);
            shopInfoAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
                @Override
                public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                    switch (view.getId()) {
                        case R.id.product_details:
                            Bundle bundle = new Bundle();
                            bundle.putString("product_id", mShopLvBeanList.get(position).getProductid());
                            bundle.putDouble("price", mShopLvBeanList.get(position).getPrice());
                            startActivityForResult(ShopDetails_Aty.class, bundle, 100);
                            break;
                    }
                }
            });
        }
        if (shopInfoBean != null) {
            if (shopInfoBean.getData() != null) {
                mShopLvBeanList.clear();
                List<ShopInfoBean.DataBean> dataBeanList = new ArrayList<>();
                dataBeanList.addAll(shopInfoBean.getData());

                if (!TextUtils.isEmpty(lv)) {
                    for (ShopInfoBean.DataBean dataBean : dataBeanList) {
                        if ((!TextUtils.isEmpty(dataBean.getLvOne_structure_id()) && dataBean.getLvOne_structure_id().equals(lv))
                                || (!TextUtils.isEmpty(dataBean.getLvTwo_structure_id()) && dataBean.getLvTwo_structure_id().equals(lv))
                                || (!TextUtils.isEmpty(dataBean.getLvThree_structure_id()) && dataBean.getLvThree_structure_id().equals(lv))) {
                            mShopLvBeanList.add(dataBean);
                            L.i("药品类型级别  筛选药品 0-====     " + mShopLvBeanList.size());
                        }
                    }
                    L.i("药品类型级别  筛选药品 1-====     " + mShopLvBeanList.size());
                } else {
                    mShopLvBeanList.addAll(dataBeanList);
                }

                shopInfoAdapter.setList(mShopLvBeanList);


            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 100) {
                if (data != null) {
                    String product_id = data.getStringExtra("product_id");
                    Double price = data.getDoubleExtra("price", 0);
                    for (int i = 0; i < mShopLvBeanList.size(); i++) {
                        ShopInfoBean.DataBean dataBean = mShopLvBeanList.get(i);
                        if (dataBean.getProductid().equals(product_id) && price == dataBean.getPrice()) {
                            addCar(i, dataBean);
                            break;
                        }
                    }
                }
            }
        }
    }

    /**
     * 购物车的控件和数据初始化
     */
    public void carShopData() {
        if (shopCarAdapter == null) {
            shopCarAdapter = new ShopCarAdapter(R.layout.main_carinfo_list_item, carShopList, this);
            mainCarshopRecyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.HORIZONTAL, false));
            mainCarshopRecyclerView.setAdapter(shopCarAdapter);
        }
    }

    /**
     * 添加到购物车
     *
     * @param position
     * @param dataBean
     */
    public void addCar(int position, ShopInfoBean.DataBean dataBean) {
        if (carShopList.size() >= purchaseCount) {
            showToast("购买数量已到达上限，不可选择");
            return;
        }
        if (dataBean.getCount() == 0) {
            Log.i("ces=", "添加到购物车 " + position + "库存==" + dataBean.getCount());
            showToast("库存不足");
            return;
        }
        carShopList.add(dataBean);
        shopCarAdapter.notifyDataSetChanged();
        int currentCount = dataBean.getCount() - 1;
        dataBean.setCount(currentCount);
        mShopLvBeanList.set(position, dataBean);
        shopInfoAdapter.notifyItemChanged(position);
        Log.i("ces=", "shopInfoAdapter点击的item  " + position + "库存==" + carShopList.toString());

    }

    /**
     * 删除购物车
     *
     * @param dataBean
     */
    public void delectCar(ShopInfoBean.DataBean dataBean) {
        for (int i = 0; i < mShopLvBeanList.size(); i++) {
            if (mShopLvBeanList.get(i).getProductid() == dataBean.getProductid()) {
                mShopLvBeanList.get(i).setCount(dataBean.getCount() + 1);
                shopInfoAdapter.notifyItemChanged(i);
            }
        }

    }

    /**
     * 检测商品是否需要医生编码弹框
     */
    public void checkProductNeedDoctor() {
        List<String> productids = new ArrayList<>();
        for (ShopInfoBean.DataBean dataBean : carShopList) {
            if (!productids.contains(dataBean.getProductid())) {
                productids.add(dataBean.getProductid());
            }
        }
        ShopApiHttp.check_product_need_doctor(productids, this);
    }

    /**
     * 创建订单
     */
    public void setCreateOrder() {
        List<ShopInfoBean.DataBean> mOrderList = new ArrayList<>();
        for (int i = 0; i < carShopList.size(); i++) {
            int postion = 0;
            boolean isadd = true;
            for (int j = 0; j < mOrderList.size(); j++) {
                if (carShopList.get(i).getProductid().equals(mOrderList.get(j).getProductid()) &&
                        carShopList.get(i).getSlotIndexs().toString().equals(mOrderList.get(j).getSlotIndexs().toString())) {
                    postion = j;
                    isadd = false;
                }
            }
            if (isadd) {
                setAddmOrderList(mOrderList, i);
            } else {
                mOrderList.get(postion).setQuantity(mOrderList.get(postion).getQuantity() + 1);
            }
        }
        L.i("上传的订单信息==", mOrderList);
        ShopApiHttp.create_order(mOrderList, doctor_bar_code, this);
    }

    public void setAddmOrderList(List<ShopInfoBean.DataBean> mOrderList, int postion) {
        ShopInfoBean.DataBean data = carShopList.get(postion);
        ShopInfoBean.DataBean dataBean = new ShopInfoBean.DataBean();
        dataBean.setQuantity(1);
        dataBean.setProductid(data.getProductid());
        dataBean.setSlotIndexs(data.getSlotIndexs());
        mOrderList.add(dataBean);
    }

    @Override
    public void onRequestStart(String requestUrl, int requestId) {

    }

    @Override
    public void onRequestComplete(String requestUrl, int requestId) {
        removeProgressDialog();

    }


    @Override
    public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
        if (requestUrl.endsWith(ShopApiHttp.get_mch_max_sale_count)) {
            L.i("获取机器可购买的数量==" + requestJson.toString());
            int count = 0;
            try {
                count = requestJson.getInt("data");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            SharedUtils.getInstance().putInt(ShareKey.PURCHASE_COUNT, count);
            purchaseCount = count;
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.get_product_type)) {
            setError(false);
            shopTypeBean = new Gson().fromJson(requestJson.toString(), (Type) ShoptypeBean.class);
            mModelList.clear();
            mModelList.addAll(shopTypeBean.getData());
            shopModelAdapter.collapseAllGroup();
            Log.i("ces=", " ==商品分类级别数据==" + shopTypeBean.toString());
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.get_product)) {
            setError(false);
            shopInfoBean = new Gson().fromJson(requestJson.toString(), (Type) ShopInfoBean.class);
            setShopListData("", shopInfoBean);
            return;
        }

        Constant.isShopShipment = false;
        if (requestUrl.endsWith(ShopApiHttp.create_order)) {

            L.i("订单信息==", requestJson.toString());
            shopOrderBean = new Gson().fromJson(requestJson.toString(), ShopOrderBean.class);
            if (shopOrderBean.getData().getType_lv() == 0) { //0是可以直接下单的
                for (ShopInfoBean.DataBean dataBean : carShopList) {
                    CarGoodsBeans beans = new CarGoodsBeans();
                    beans.setCount(1);
                    beans.setPrice(dataBean.getPrice());
                    beans.setProductid(dataBean.getProductid());
                    beans.setProductimg(dataBean.getProductimg());
                    beans.setProductname(dataBean.getProductname());
                    beans.setMslotIndexs(new Gson().toJson(dataBean.getSlotIndexs()));
                    beans.setIs_insurance(dataBean.isIs_insurance() ? 1 : 0);
                    beans.setIs_remote(dataBean.isIs_remote() ? 1 : 0);
                    beans.setIs_true_name(dataBean.isIs_true_name() ? 1 : 0);
                    beans.setIs_prescription(dataBean.isIs_prescription() ? 1 : 0);
                    beans.setSpec(dataBean.getSpec());
                    Log.i("ces=", " ==保存的数据==" + beans.toString());
                    FinalDbUtils.getInstance().save(beans);
                }
                todoAty(ShopPayType_Aty.class);//调转到选择支付方式页

            } else {
                showToast("该商品不能进行下单，请选择其它商品");
            }
            return;
        }

        if (requestUrl.endsWith(ShopApiHttp.check_product_need_doctor)) {
            try {
                JSONObject data = requestJson.getJSONObject("data");
                boolean need_box = data.getBoolean("need_box");
                if (need_box) {
                    showDialogQrCodex();
                } else {
                    setCreateOrder();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }

        if (requestUrl.endsWith(ShopApiHttp.check_doctor)) {
            try {
                JSONObject data = requestJson.getJSONObject("data");
                doctor_bar_code = data.getString("doctor_id");
                setCreateOrder();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.get_mch_logo)) {
            String data = requestJson.optString("data");
            try {
                JSONObject dataObject = new JSONObject(data);
                String logo_img = dataObject.getString("logo_img");
                String Name = logo_img.substring(logo_img.lastIndexOf("/")).substring(1);
                File logoFile = new File(Constant.FilePath.ICON_PATH + Name);

                if (!logoFile.exists()) {
                    L.i("logo  地址=文件不存在，准备下载=");
                    SharedUtils.getInstance().putString(ShareKey.LOGOIMG, logo_img);
                    Intent intent = new Intent(this, MyFileOtherService.class);
                    intent.putExtra("logo_img", logo_img);
                    startService(intent);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {
        if (requestUrl.endsWith(ShopApiHttp.get_product_type)) {
            L.i("get_product_type  ", errorMsg);
            showToast(errorMsg);
            setError(true);
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.get_product)) {
            setError(true);
            showToast(errorMsg);
            L.i("get_product  ", errorMsg);
            return;
        }
        Constant.isShopShipment = false;
        if (requestUrl.endsWith(ShopApiHttp.create_order)) {
            showToast(errorMsg);
            L.i("create_order  ", errorMsg);
        }
        if (requestUrl.endsWith(ShopApiHttp.check_product_need_doctor)) {
            showToast(errorMsg);
            L.i("check_product_need_doctor  ", errorMsg);
            return;
        }
        if (requestUrl.endsWith(ShopApiHttp.check_doctor)) {
            showToast(errorMsg);
            L.i("check_doctor  ", errorMsg);
        }
    }

    public void setError(boolean isShow) {
        errordata_ly.setVisibility(isShow ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        if ("货道更新".equals(event.getType())) {
            L.i("货道更新  ", "开始请求数据 更新货道");
            carShopList.clear();
            shopCarAdapter.notifyDataSetChanged();
            setDataProduct("", "", "");
            return;
        }
        if (event.getType().equals("adv_type") && "跳转广告页".equals(event.getMessage())) {
            startActivity(Adv_Aty.class, null);
            finish();
            return;
        }
        if (event.getType().equals("湿度值")) {
            mainHumidity.setText("湿度 " + event.getMessage() + "%");
        }
        if (event.getType().equals("温度值")) {
            mainTemperature.setText("温度 " + event.getMessage() + "℃");
            return;
        }
        if (event.getType().equals(Type_toGoshopzl)) {
            mCancelTime();
            L.i("检测商品是否需要医生编码弹框");
            checkProductNeedDoctor();
            return;
        }
        if (event.getType().equals("扫码code")) {
            if (!isQrCode && (mQrCodexToast != null && mQrCodexToast.isShow())) {
                isQrCode = true;
                doctor_bar_code = event.getMessage();
                showProgressDialog("创建订单中，请等待...");
                setCreateOrder();
            }
            return;
        }
        if (event.getType().equals(ShareKey.LOGOIMG)) {
            initTitleBar(advType == Constant.AdvType.NONE);
        }
    }

    /**
     * 跳转页面
     *
     * @param mclass
     */
    public void todoAty(Class mclass) {
        doStartActivity(mclass, GsonUtils.toJson(shopOrderBean));
    }

    CountTimeUtils countTimeUtils;

    /**
     * 开始计时
     *
     * @param mStartTime
     * @param type
     */
    public void startTime(long mStartTime, int type) {
        mCancelTime();
        countTimeUtils = new CountTimeUtils(mStartTime) {
            @Override
            public void onTick(long mMillisUntilFinished) {
                if (qrcode_time_tv != null) {
                    qrcode_time_tv.setText(mMillisUntilFinished + "s");
                }
            }

            @Override
            public void onFinish() {
                L.i("onFinish=", "时间到    ");
                if (type == 0) {
                    Constant.isShopShipment = false;
                    showErrorLongToast("底层通信异常，请检查机器", 6000);
                } else {
                    qrcdoeXtoastCancal();
                }
            }
        };
        countTimeUtils.start();
    }

    /**
     * 取消计时
     */
    public void mCancelTime() {
        if (countTimeUtils != null) {
            countTimeUtils.cancel();
            countTimeUtils = null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.i("释放数据");
        mHandle.removeCallbacksAndMessages(null);
        mHandle = null;
        shopTypeBean = null;
        shopModelAdapter = null;
        shopInfoBean = null;
        shopTyepAdapter = null;
        mlist.clear();
        mModelList.clear();
        shopInfoAdapter = null;
        mShopLvBeanList.clear();
        shopCarAdapter = null;
        carShopList.clear();
        shopOrderBean = null;
        Constant.isShopShipment = false;
    }

    XToast mQrCodexToast;
    Timer qrcodeTimer;//反扫的指令计时
    TimerTask qrTimerTask;
    int CommandCount = 0;//发送指令的次数
    boolean isQrCode;
    String doctor_bar_code;
    TextView qrcode_time_tv;

    /**
     * 反扫  编码 弹框
     */
    public void showDialogQrCodex() {
        CommandCount = 0;
        List<String> codes = new ArrayList<>();
        StringBuilder sbfcode = new StringBuilder();//条码
        View toastView = LayoutInflater.from(this).inflate(R.layout.item_qrcode, null);
        mQrCodexToast = new XToast(this).setView(toastView);
        mQrCodexToast.setAnimStyle(android.R.style.Animation_Toast);
        mQrCodexToast.setBackgroundDimAmount(0.6f);
        mQrCodexToast.setWidth(PxUtils.dp2px(this,1000));


        mQrCodexToast.setGravity(Gravity.CENTER_VERTICAL);
        mQrCodexToast.setOutsideTouchable(false);
        qrcode_time_tv = toastView.findViewById(R.id.qrcode_time_tv);
        startTime(60, 1);
        TextView qrcode_alter_tv = toastView.findViewById(R.id.qrcode_alter_tv);
        TextView qrcode_back = toastView.findViewById(R.id.qrcode_back);
        ImageView fscode_img = toastView.findViewById(R.id.fscode_img);
        boolean medicine_is_scan = SharedUtils.getInstance().getBoolean(ShareKey.medicine_is_scan, false);
        String medicine_scan_alert = SharedUtils.getInstance().getString(ShareKey.medicine_scan_alert, "");
        if (!medicine_scan_alert.equals("null") && !TextUtils.isEmpty(medicine_scan_alert)) {
            qrcode_alter_tv.setText(medicine_scan_alert);
        }
        if (medicine_is_scan) {
            mQrCodexToast.setHeight(PxUtils.dp2px(this,1400));
            fscode_img.setVisibility(View.VISIBLE);
            qrcodeTimer = new Timer();
            qrTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (CommandCount > 2) {
                        qrcdoeCancal();
                        return;
                    }
                    QrCodeUtils.sendCommandCode();
                    CommandCount++;
                }
            };
            qrcodeTimer.schedule(qrTimerTask, 100, 20100);
        } else {
            mQrCodexToast.setHeight(PxUtils.dp2px(this,800));
            fscode_img.setVisibility(View.GONE);
        }
        qrcode_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                qrcdoeCancal();
                qrcdoeXtoastCancal();
            }
        });
        mQrCodexToast.show();
        codes.add("1");
        codes.add("2");
        codes.add("3");
        codes.add("4");
        codes.add("5");
        codes.add("6");
        codes.add("7");
        codes.add("8");
        codes.add("9");
        codes.add("删除");
        codes.add("0");
        codes.add("确认");


        TextView qhcodeClear = toastView.findViewById(R.id.qhcode_clear);
        TextView qhcodeNumberTv = toastView.findViewById(R.id.qhcode_number_tv);
        qhcodeClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sbfcode.delete(0, sbfcode.length());
                qhcodeNumberTv.setText("");
            }
        });

        GridView qhcodeGridView = toastView.findViewById(R.id.qhcode_gridView);
        QrCodeAdapter qrCodeAdapter = new QrCodeAdapter(this, codes);
        qhcodeGridView.setAdapter(qrCodeAdapter);
        qhcodeGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                L.i("tjf=codes=" + position);
                if (codes.get(position).equals("删除")) {
                    if (sbfcode.length() > 0) {
                        sbfcode.delete(sbfcode.length() - 1, sbfcode.length());
                        qhcodeNumberTv.setText(sbfcode.toString());
                    }
                } else if (codes.get(position).equals("确认")) {
                    if (sbfcode.length() >= 0) {
                        if (!isQrCode) {
                            isQrCode = true;
                            L.i("tjf=codes确认=" + sbfcode.toString());
                            showProgressDialog("编码检测中，请等待...");
                            ShopApiHttp.check_doctor(sbfcode.toString(), ShopMain_Aty.this);
                        }
                    } else {
                        showErrorLongToast("条码长度太短，请重新输入", 5000);
                    }
                } else {
                    if (sbfcode.length() >= 18) {
                        showErrorToast("条码长度已到最大值，无法输入");
                        return;
                    }
                    sbfcode.append(codes.get(position));
                    qhcodeNumberTv.setText(sbfcode.toString());
                }
            }
        });
    }


    public void qrcdoeCancal() {
        L.i("取消计时发送识别扫码指令");
        if (qrTimerTask != null) {
            qrTimerTask.cancel();
            qrTimerTask = null;
        }
        if (qrcodeTimer != null) {
            qrcodeTimer.purge();
            qrcodeTimer.cancel();
            qrcodeTimer = null;
        }
    }

    public void qrcdoeXtoastCancal() {
        L.i("取消弹框");
        mCancelTime();
        if (mQrCodexToast != null) {
            mQrCodexToast.cancel();
            mQrCodexToast = null;
        }
    }
}
